import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../providers/song_provider.dart';
import '../models/song.dart';
import '../services/download_manager.dart';
import '../services/audio_player_service.dart';
import '../services/database_service.dart';

class PlaylistView extends StatefulWidget {
  final Function(Song)? onSongSelected;

  const PlaylistView({
    Key? key,
    this.onSongSelected,
  }) : super(key: key);

  @override
  State<PlaylistView> createState() => _PlaylistViewState();
}

class _PlaylistViewState extends State<PlaylistView> {
  @override
  Widget build(BuildContext context) {
    return Consumer<SongProvider>(
      builder: (context, songProvider, child) {
        final songs = songProvider.songs;

        final hotSongs = songs.where((song) => song.isHot).toList();
        final normalSongs = songs.where((song) => !song.isHot).toList();

        final loadingSongs = songs.where((song) => song.isDownloading).toList();

        final audioPlayer = AudioPlayerService();
        audioPlayer.setPlaylist(loadingSongs);

        return Column(
          children: [
            if (hotSongs.isNotEmpty) ...[
              const Padding(
                padding: EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
                child: Row(
                  children: [
                    Icon(Icons.local_fire_department,
                        color: Colors.red, size: 16),
                    SizedBox(width: 4),
                    Text('热门歌曲',
                        style: TextStyle(
                            fontSize: 12, fontWeight: FontWeight.bold)),
                  ],
                ),
              ),
              const Padding(
                padding: EdgeInsets.symmetric(horizontal: 8.0),
                child: Divider(height: 1),
              ),
              Expanded(
                flex: 2,
                child: _buildSongGrid(hotSongs),
              ),
            ],
            const SizedBox(
              height: 16,
            ),
            const Padding(
              padding: EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
              child: Row(
                children: [
                  Icon(Icons.queue_music, size: 16),
                  SizedBox(width: 4),
                  Text('历史歌曲',
                      style:
                          TextStyle(fontSize: 12, fontWeight: FontWeight.bold)),
                ],
              ),
            ),
            const Padding(
              padding: EdgeInsets.symmetric(horizontal: 8.0),
              child: Divider(height: 1),
            ),
            Expanded(
              flex: normalSongs.isEmpty ? 1 : 4,
              child: _buildSongGrid(normalSongs),
            ),
          ],
        );
      },
    );
  }

  Widget _buildSongGrid(List<Song> songs) {
    final audioPlayer = AudioPlayerService();

    return GridView.builder(
      padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 2.0),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        childAspectRatio: 3.2,
        crossAxisSpacing: 3.0,
        mainAxisSpacing: 3.0,
      ),
      itemCount: songs.length,
      itemBuilder: (context, index) {
        final song = songs[index];
        final bool isPlaying =
            AudioPlayerService().currentSong?.songId == song.songId;
        return Card(
          elevation: 1.0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(4.0),
          ),
          child: InkWell(
            onTap: () async {
              if (song.isDownloaded) {
                try {
                  widget.onSongSelected?.call(song);
                } catch (e) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('播放失败: $e')),
                  );
                }
              } else {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                      content:
                          Text('歌曲 ${song?.artist}《${song?.title}》下载中...')),
                );
                await _downloadSong(song);
                final songNew =
                    await Provider.of<SongProvider>(context, listen: false)
                        .getById(song.songId);
                if (songNew != null) {
                  try {
                    widget.onSongSelected?.call(songNew);
                    await audioPlayer.playSong(songNew);
                  } catch (e) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('播放失败: $e')),
                    );
                  }
                }
              }
            },
            child: Padding(
              padding:
                  const EdgeInsets.symmetric(horizontal: 16.0, vertical: 1.0),
              child: Row(
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          song.title,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            fontSize: 12,
                            color: isPlaying ? Colors.blue : Colors.black87,
                          ),
                        ),
                        const SizedBox(height: 1.0),
                        Text(
                          song.artist,
                          style: const TextStyle(
                            fontSize: 10.0,
                            color: Colors.grey,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                    ),
                  ),
                  SizedBox(
                    width: 24,
                    child: _buildDownloadIcon(song),
                  ),
                  const SizedBox(width: 4),
                  if (!song.isHot) // 只为非热门歌曲显示删除按钮
                    IconButton(
                      icon: const Icon(Icons.delete_outline,
                          color: Colors.orange, size: 18),
                      padding: EdgeInsets.zero,
                      constraints: const BoxConstraints(),
                      onPressed: () {
                        showDialog(
                          context: context,
                          builder: (context) => AlertDialog(
                            title: const Text('删除歌曲'),
                            content: Text('确定要删除 ${song.title} 吗？'),
                            actions: [
                              TextButton(
                                onPressed: () => Navigator.pop(context),
                                child: const Text('取消'),
                              ),
                              TextButton(
                                onPressed: () async {
                                  Navigator.pop(context);
                                  // 如果正在播放这首歌，先停止播放
                                  if (isPlaying) {
                                    await AudioPlayerService().stop();
                                  }
                                  // 删除歌曲
                                  await Provider.of<SongProvider>(context,
                                          listen: false)
                                      .deleteSong(song);
                                },
                                child: const Text('删除'),
                              ),
                            ],
                          ),
                        );
                      },
                    ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildDownloadIcon(Song song) {
    if (song.isDownloading) {
      return Container(
        width: 24,
        height: 24,
        padding: const EdgeInsets.all(3),
        child: const CircularProgressIndicator(
          strokeWidth: 2,
          valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
        ),
      );
    } else if (song.isDownloaded) {
      return IconButton(
        icon: const Icon(
          Icons.south_east,
          size: 18,
          color: Colors.green,
        ),
        tooltip: '导出歌曲',
        padding: EdgeInsets.zero,
        constraints: const BoxConstraints(),
        onPressed: () async {
          final success =
              await Provider.of<SongProvider>(context, listen: false)
                  .exportSong(song);
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text(
                  success ? '歌曲已导出到下载目录' : '导出失败，请检查权限和磁盘空间',
                ),
                duration: const Duration(seconds: 2),
              ),
            );
          }
        },
      );
    } else {
      return Icon(
        Icons.download,
        size: 18,
        color: Colors.grey[400],
      );
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  Future<void> _downloadSong(Song song) async {
    try {
      // 更新下载状态到数据库
      await Provider.of<SongProvider>(context, listen: false)
          .updateDownloadingStatus(song, true);

      final database = await DatabaseService().database;
      final (localPath, lyrics) =
          await DownloadManager.downloadSongAndLyrics(song, database);

      if (localPath != null && lyrics != null) {
        await Provider.of<SongProvider>(context, listen: false)
            .updateSongDownloadStatus(song, true, localPath, lyrics);
      }

      // 完成后重置下载状态
      await Provider.of<SongProvider>(context, listen: false)
          .updateDownloadingStatus(song, false);
    } catch (e) {
      // 发生错误时也要重置下载状态
      await Provider.of<SongProvider>(context, listen: false)
          .updateDownloadingStatus(song, false);

      print('下载失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('下载失败: $e')),
        );
      }
    }
  }
}
